<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas to PNG Download</title>
</head>
<body>
    <canvas id="myCanvas" width="200" height="200"></canvas>
    <button id="downloadButton">下载图像</button>
    <script>
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d');

        // 绘制一个红色的矩形
        ctx.fillStyle = 'red';
        ctx.fillRect(50, 50, 100, 100);

        // 获取下载按钮
        var downloadButton = document.getElementById('downloadButton');

        // 为下载按钮添加点击事件监听器
        downloadButton.addEventListener('click', function() {
            // 将 canvas 内容转换为 PNG 图像的 DataURL
            var dataURL = canvas.toDataURL('image/png');

            // 通过设置 window.location 来触发浏览器下载
            window.location = dataURL;

            // 可选：为下载的文件命名
            var a = document.createElement('a');
            a.href = dataURL;
            a.download = 'canvas-dow.png';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        });
    </script>
</body>
</html>